import _ from 'lodash';
import React, {Fragment} from "react";
import View from "../base/View";
import defaultData from "./data";
import {WeaInput, WeaSelect} from "ecCom";
import {detailTypes, OTHER} from "../../../../../constants/form";
import types from "./types";
import './View.less';

const { RADIO, CHECKBOX } = detailTypes;

export default class SelectView extends View {
  state = {
    otherValue: ''
  };

  formatValue = value => {
    const { otherValue } = this.state;
    const vals = value.split(',');
    const newValue = vals.map(val => ({
      key: val,
      value: OTHER === val ? otherValue : ''
    }));

    return newValue;
  }

  handleOtherValueChange = otherValue => {
    const { value } = this.props;
    const other = value.find(({ key }) => OTHER === key);

    this.setState({ otherValue });

    if(!other) return;

    other.value = otherValue;

    this.props.onChange([...value]);
  }

  getOpts(options) {
    const {otherValue} = this.state;
    return options.map(opt => {
      const newOpt = { ...opt };

      if(OTHER === opt.key && _.isString(opt.showname)) {
        newOpt.showname = (
          <Fragment>
            {opt.showname}
            <WeaInput
                value={otherValue}
              onChange={this.handleOtherValueChange}
              onFocus={this.selectOtherOpt}
            />
          </Fragment>
        );
      }

      return newOpt;
    });
  }

  selectOtherOpt = () => {
    const { value, data } = this.props;
    let values = value.map(({ key }) => key);

    if(values.includes(OTHER)) return;

    if(types.CHECKBOX === data.type) {
      values.push(OTHER);
      values = values.join(',');
    } else {
      values = OTHER;
    }

   const newValue = this.formatValue(values);

    this.props.onChange(newValue);
  };

  renderContent(data, value) {
    const { options, type } = data;
    const detailtype = type === types.CHECKBOX ? CHECKBOX : RADIO;
    const vals = value.map(({ key, value }) => {
      if(OTHER === key){
        this.state.otherValue = value;
      }
      return key;
    }).join(',');

    const opts = this.getOpts(options);

    return (
      <WeaSelect
        value={vals}
        key={detailtype} // 用于强制更新组件类型
        options={opts}
        detailtype={detailtype}
        supportCancel
        onChange={this.handleValueChange}
      />
    );
  }

  renderForReadonly(data, value) {
    let options = {};
    data.options.map(({key, showname}) => {
      options[key] = showname;
    });

    return (
        <ul>
          {value.map(({ key, value }) => (

              <li>{value || options[key]}</li>
          ))}
        </ul>
    )
  }
}

SelectView.defaultProps = {
  data: defaultData,
  value: []
};